package com.darren.euc.action;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.darren.euc.entity.HanWangDoor;
import com.darren.euc.entity.PageBean;
import com.darren.euc.entity.ResponseJSON;
import com.darren.euc.entity.Room;
import com.darren.euc.entity.User;
import com.darren.euc.service.HanWangDoorService;
import com.darren.euc.service.RoomService;
import com.darren.euc.util.HanWangUtil;
import com.darren.euc.util.PropertyHelper;

import net.sf.json.JSONObject;

@Controller
@RequestMapping("/hanwang")
public class HanWangDoorAction {
	
	private static final Logger log = Logger.getLogger(HanWangDoorAction.class);
	
	@Autowired
    private HanWangDoorService hanWangDoorService;
	
	@Autowired
    private RoomService roomService;
	
	
	@ResponseBody
    @RequestMapping(value = "/list")
    public List<HanWangDoor> getAllFunctions(HttpServletRequest request,HttpServletResponse response) {
    	List<HanWangDoor> hanWangDoors = hanWangDoorService.getAll();    	
        return hanWangDoors;
    }
	
	@ResponseBody
    @RequestMapping(value = "/bind/{memberId}")
    public ResponseJSON bindMemberCard(@PathVariable("memberId") Integer  memberId,HttpServletRequest request,HttpServletResponse response) {
    	ResponseJSON responseJson = new ResponseJSON();    	
    	String result = hanWangDoorService.bindingCard(memberId);
    	if("".equals(result)){
    		responseJson.setStatus(0);
    		responseJson.setMessage("绑卡成功！");
    	}else{
    		responseJson.setStatus(-1);
    		responseJson.setMessage(result);
    	} 
        return responseJson;
    }
	
	
	@ResponseBody
    @RequestMapping(value = "/bindemployee/{spaceId}")
    public ResponseJSON bindEmployee(@PathVariable("spaceId") Integer  spaceId,HttpServletRequest request,HttpServletResponse response) {
    	ResponseJSON responseJson = new ResponseJSON();    	
    	String result = hanWangDoorService.bindingEmployeeCard(spaceId);
    	if("".equals(result)){
    		responseJson.setStatus(0);
    		responseJson.setMessage("更新工作人员信息成功！");
    	}else{
    		responseJson.setStatus(-1);
    		responseJson.setMessage("更新工作人员信息失败！");
    	} 
        return responseJson;
    }
	
	
	@ResponseBody
    @RequestMapping(value = "/updateManager/{spaceId}")
    public ResponseJSON updateHanWangManager(@PathVariable("spaceId") Integer  spaceId,HttpServletRequest request,HttpServletResponse response) {
    	ResponseJSON responseJson = new ResponseJSON();
    	String result = hanWangDoorService.updateHanWangManager(spaceId);
    	if("".equals(result)){
    		responseJson.setStatus(0);
    		responseJson.setMessage("更新管理员信息成功！");
    	}else{
    		responseJson.setStatus(-1);
    		responseJson.setMessage("更新管理员信息失败！");
    	} 
        return responseJson;
    }
	
	
	@ResponseBody
    @RequestMapping(value = "/unbind/{memberId}")
    public ResponseJSON unbindMemberCard(@PathVariable("memberId") Integer  memberId,HttpServletRequest request,HttpServletResponse response) {
    	ResponseJSON responseJson = new ResponseJSON();
    	String result =  hanWangDoorService.unbindingCard(memberId);
    	if("".equals(result)){
    		responseJson.setStatus(0);
    		responseJson.setMessage("解绑成功！");
    	}else{
    		responseJson.setStatus(-1);
    		responseJson.setMessage(result);
    	}   	
        return responseJson;
    }
	
	@ResponseBody
    @RequestMapping(value = "/spaceroom",method = RequestMethod.POST)
    public List<Room> getRoomsBySpaceId(@RequestBody JSONObject requestJson,HttpServletRequest request,HttpServletResponse response) {
		List<Room> rooms = null;
		try{
			Integer spaceId = requestJson.getInt("spaceId");
	    	rooms = roomService.findRoomBySpaceId(spaceId); 
		}catch(Exception ex){
			rooms = new ArrayList<Room>();
			log.error(ex.getMessage(),ex);
		}
        return rooms;
    }

	
	@SuppressWarnings("rawtypes")
	@ResponseBody
    @RequestMapping(value = "/query",method = RequestMethod.POST)
    public ResponseJSON queryHanWangDoor(@RequestBody JSONObject requestJson,HttpServletRequest request,HttpServletResponse response) {	
		ResponseJSON responseJson = new ResponseJSON();
		PageBean pageBean = hanWangDoorService.queryForPageUseHQL(requestJson.getJSONObject("data"), PropertyHelper.getPageSize(), requestJson.getInt("currentPage"));
		responseJson.setData(pageBean);
		return responseJson;
    }

	
	@ResponseBody
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public ResponseJSON saveHanWangDoor(@RequestBody HanWangDoor hanWangDoor,HttpServletRequest request,HttpServletResponse response) {	
		ResponseJSON responseJson = new ResponseJSON();
		try {
			User user = (User) request.getAttribute("user");
			if(user != null){
				hanWangDoor.setCreatedBy(user.getId().toString());
				hanWangDoor.setLastModifyBy(user.getId().toString());
			}
			hanWangDoor.setCreateTime(new Date());
			hanWangDoor.setLastModifyTime(new Date());
			hanWangDoor.setConnectStatus(2);
			hanWangDoor = hanWangDoorService.save(hanWangDoor);
			responseJson.setStatus(0);
			responseJson.setMessage("添加成功！");
		} catch (Exception ex) {
			log.info(ex.getMessage(), ex);
			responseJson.setStatus(-1);
			responseJson.setMessage("添加失败！");
		}
		responseJson.setData(hanWangDoor);
		System.out.println("==============================================================");
		System.out.println(responseJson.toString());
		System.out.println("==============================================================");
		return responseJson;
    }
	
	@ResponseBody
    @RequestMapping(value = "/delete",method = RequestMethod.POST)
    public ResponseJSON deleteRole(@RequestBody JSONObject requestJson,HttpServletRequest request,HttpServletResponse response) {
    	ResponseJSON responseJson = new ResponseJSON();
    	JSONObject jsonData = new JSONObject();
    	responseJson.setData(jsonData);
    	try{
    		Integer id = Integer.parseInt(requestJson.getString("id"));
    		HanWangDoor hanWangDoor = hanWangDoorService.findById(id);
    		hanWangDoor.setEnable(false);
    		hanWangDoor.setMain(false);
    		hanWangDoor.setConnectStatus(2);
    		hanWangDoor = hanWangDoorService.update(hanWangDoor);
    		responseJson.setData(hanWangDoor);
    		responseJson.setMessage("删除成功！");
    	}catch(Exception ex){
    		log.info(ex.getMessage(),ex);
        	responseJson.setStatus(-1);
    		responseJson.setMessage("删除失败！");
    	}
    	System.out.println("==============================================================");
    	System.out.println(requestJson.toString());
    	System.out.println(responseJson.toString());
    	System.out.println("==============================================================");
        return responseJson;
    }
	  
	@ResponseBody
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public ResponseJSON updateHanWangDoor(@RequestBody HanWangDoor hanWangDoor, HttpServletRequest request,
			HttpServletResponse response) {
		ResponseJSON responseJson = new ResponseJSON();
		try {
			User user = (User) request.getAttribute("user");
			if(user != null){
				hanWangDoor.setLastModifyBy(user.getId().toString());
			}
			hanWangDoor.setLastModifyTime(new Date());
			hanWangDoor = hanWangDoorService.update(hanWangDoor);			
			responseJson.setStatus(0);
			responseJson.setMessage("保存成功！");
		} catch (Exception ex) {
			log.info(ex.getMessage(), ex);
			responseJson.setStatus(-1);
			responseJson.setMessage("保存失败！");
		}
		responseJson.setData(hanWangDoor);
		System.out.println("==============================================================");
		System.out.println(responseJson.toString());
		System.out.println("==============================================================");
		return responseJson;
	}
	
	/**
	 * 将设备设备为空间主设备
	 * @param hanWangDoor
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/main", method = RequestMethod.POST)
	public ResponseJSON updateEnableHanWangDoor(@RequestBody HanWangDoor hanWangDoor, HttpServletRequest request,
			HttpServletResponse response) {
		ResponseJSON responseJson = new ResponseJSON();
		try {
			
			List<HanWangDoor> hanWangDoors = hanWangDoorService.getMainHanWangDoorBySpaceIdNotEquelsId(hanWangDoor.getSpaceId(),hanWangDoor.getId());
			if(hanWangDoors != null && hanWangDoors.size() > 0){
				responseJson.setStatus(0);
				responseJson.setMessage(String.format("空间【%s】已有主设备,请先取消【%s】的主设备状态 ！",hanWangDoors.get(0).getSpaceName(),hanWangDoors.get(0).getDeviceName()));
			}else{
				User user = (User) request.getAttribute("user");
				if(user != null){
					hanWangDoor.setLastModifyBy(user.getId().toString());
				}
				hanWangDoor.setLastModifyTime(new Date());
				hanWangDoor.setMain(true);
				hanWangDoor = hanWangDoorService.update(hanWangDoor);			
				responseJson.setStatus(0);
				responseJson.setMessage("设置主设备成功！");
			}
		} catch (Exception ex) {
			log.info(ex.getMessage(), ex);
			responseJson.setStatus(-1);
			responseJson.setMessage("设置主设备失败！");
		}
		responseJson.setData(hanWangDoor);
		System.out.println("==============================================================");
		System.out.println(responseJson.toString());
		System.out.println("==============================================================");
		return responseJson;
	}
	
	/**
	 * 将设备设备为空间主设备
	 * @param hanWangDoor
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/addinfo", method = RequestMethod.POST)
	public ResponseJSON setTestMemberInfoToHanWang(@RequestBody JSONObject requestJson, HttpServletRequest request,
			HttpServletResponse response) {
		ResponseJSON responseJson = new ResponseJSON();
		try {
			JSONObject employeeJson = requestJson.getJSONObject("employee");
			String spaceId = requestJson.getString("spaceId");
			List<HanWangDoor> mainHanWang = hanWangDoorService.getMainHanWangDoorBySpaceId(Integer.parseInt(spaceId));
			if(mainHanWang != null && mainHanWang.size() > 0){
				Map<String,Object> mainDevice = hanWangDoorService.hanWangDoorDevice(mainHanWang.get(0));
				String result = HanWangUtil.setTestMemberInfoToHanWang(mainDevice, employeeJson);
				responseJson.setMessage(result);;
			}else{
				responseJson.setMessage("未找到指定空间的前台设备！");
			}
		} catch (Exception ex) {
			log.info(ex.getMessage(), ex);
			responseJson.setStatus(-1);
			responseJson.setMessage("设置失败！");
		}
		System.out.println("==============================================================");
		System.out.println(responseJson.toString());
		System.out.println("==============================================================");
		return responseJson;
	}
	
}